from flask import Flask,request
from flask_sqlalchemy import SQLAlchemy
from  flask_migrate import Migrate

from flask_login import LoginManager
from config import Config,basedir
import os
from flask_mail import Mail

import logging
from logging.handlers import SMTPHandler,RotatingFileHandler

from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_babel import Babel

#引入配置文件 这样做的目的时松耦合
app = Flask(__name__)
app.config.from_object(Config)

login_manager = LoginManager()
login_manager.login_view = 'login'

#Moment.js 转换utc时间到各个时区进行显示
moment = Moment(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login_manager.init_app(app)
mail = Mail(app)
bootstrap = Bootstrap(app)

#本地化和国际化
babel = Babel(app)
@babel.localeselector
def get_locakeselector():
    return request.accept_languages.best_match(app.config['LANGUAGES'])


if not app.debug:
    """
    if app.config['MAIL_SERVER']:
        auth = None
        if app.config['MIAL_USENAME'] or app.config["MAIL_PASSWORD"]:
            auth = (app.config["MAIL_USERNAME"],app.config['MAIL_PASSWORD'])
        secure = None
        if app.config['MAIL_USE_TLS']:
            secure = ()

        main_handler = SMTPHandler(
            mailhost=(app.config['MAIL_SERVER'],app.config['MAIL_PORT']),
            fromaddr='no-reply@'+app.config['MAIL_SERVER'],
            toaddrs=app.config['ADMIINS'],subject='Mocroblog Failure',
            credentials=auth,secure=secure
        )
        main_handler.setLevel(logging.ERROR)
        app.logger.addHandler(main_handler)
        """
    ###记录日志到文件中
    if not os.path.exists(basedir+'/logs'):
        os.makedirs(basedir+'/logs')
    file_handler = RotatingFileHandler(basedir+'/logs/mega.log',maxBytes=102400,backupCount=10)
    file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)

    app.logger.setLevel(logging.INFO)
    app.logger.info("magelog start up")


